from cou.api_1_0 import api
from cou.models import taocan
from flask import jsonify,current_app,request
from cou.utils.response_code import RET
from cou import redis_store
from cou.utils.constants import AREA_INFO_TIME_OUT
import json
from cou.utils.constants import TAOCAN_NUM
@api.route('/areas')
def get_area():
    return jsonify(errno=RET.OK,errmsg="成功",data=[
        {'aid':1,'aname':'暨南大学番禺校区'},
        {'aid':2,'aname':'暨南大学石牌校区'}
    ])

@api.route("/taocans/index")
def get_index_taocan():
    t=taocan.query.order_by(taocan.price).limit(5).all()
    taocan_return=[i.get_basic_info() for i in t]
    return jsonify(errno=RET.OK,errmsg="成功",data=taocan_return)
@api.route('/taocans/<int:taocan_id>')
def get_taocan_detail(taocan_id):
    t=taocan.query.filter_by(id=taocan_id).first()
    return jsonify(errno=RET.OK,errmsg="成功",data={'taocan':t.get_basic_info()})
@api.route('/taocans')
def get_taocans():
    aid=request.args.get('aid')
    sd=request.args.get('sd')
    ed=request.args.get('ed')
    sk=request.args.get('sk')
    try:
        page=int(request.args.get('p'))
    except Exception as e:
        page=1
        current_app.logger.error(e)
    
    filters=[]
    print('aid',aid)
    if aid:
        filters.append(taocan.areaId==aid)
    
    if sd:
        try:
            sd=int(float(sd)*100)
        except Exception as e:
            current_app.logger.error(e)
        else:
            filters.append(taocan.price>=sd)
    if ed:
        try:
            ed=int(float(ed)*100)
        except Exception as e:
            current_app.logger.error(e)
        else:
            filters.append(taocan.price<=ed)
    sort_key=None
    if sk == 'new':
        sort_key=taocan.create_time.desc()
    # elif sk == 'booking':
    #     sort_key=taocan.check_time.desc()
    elif sk =='price-inc':
        sort_key=taocan.price
    elif sk =='price-des':
        sort_key=taocan.price.desc()
    else:
        sort_key=taocan.create_time.desc()

    try:
        paginate=taocan.query.filter(*filters).order_by(sort_key).paginate(page,TAOCAN_NUM,False)
    except Exception as e:
        current_app.logger.error(e)
    pages=paginate.pages
    taocans=paginate.items
    
    
    taocans_return=[]
    for i in taocans:
        taocans_return.append(i.get_basic_info())
    return jsonify(errno=RET.OK,errmsg="成功",data={'total_page':pages,'taocans':taocans_return})

    

